package com.sanalkitaplik.mail;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class MailManager {
	
	private String from;
	private String host;
	private String username;
	private String password;
	private ArrayList<String> toList;
	private String subject;
	private String message;

	public MailManager() {
		from = "sanalkitaplik@gmail.com";
		host = "smtp.gmail.com";
	    username = "sanalkitaplik";
	    password = "adibendesakli123456";
		toList = new ArrayList<String>();
		subject = "";
		message = "";
	}
	
	public void addTo(String address) {
		toList.add(address);
	}
	
	public void removeTo(String address) {
		for (int i=0; i<toList.size(); i++) {
			if (toList.get(i).equals(address))
				toList.remove(i);
		}
	}
	
	public void clearToList() {
		toList.clear();
	}
	
	public void setSubject(String subject) {
		this.subject = subject;
	}
	
	public String getSubject() {
		return this.subject;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}
	
	public String getMessage() {
		return this.message;
	}
	
	public void appendMessage(String message) {
		this.message += message;
	}
	
	public void clearMessage() {
		this.message = "";
	}
	
	public void send() {
		Properties props = new Properties();
		props.put("mail.smtps.auth", "true");
		props.put("mail.smtp.host", host);
		props.put("mail.debug", "true");
		Session session = Session.getInstance(props);
		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] address = new InternetAddress[toList.size()];
			for (int i=0; i<address.length; i++)
				address[i] = new InternetAddress(toList.get(i));
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setSubject(subject);
			msg.setSentDate(new Date());
			msg.setText(message);
			Transport t = session.getTransport("smtps");
			t.connect(host, username, password);
			t.sendMessage(msg, msg.getAllRecipients());
		} catch (MessagingException mex) {
			mex.printStackTrace();
		}
	}
}